﻿using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Org.BouncyCastle.OpenSsl;

namespace Dotnet.Utils.Utility.EncryptUtil.Ins
{
    public class RsaUtil
    {
        public static void Main()
        {

            var deStr = RsaUtil.Decrypt("Ins123Ces!");
            string decrypt = RsaUtil.Decrypt(deStr);

            var deStr2 = RsaUtil.RsaEncryptWithPublic("Ins123Ces!" + "|" + RsaUtil.GetTimeStamp());
            string decrypt2 = RsaUtil.Decrypt(deStr2);
            if (!string.IsNullOrWhiteSpace(decrypt2) && decrypt2.Contains('|'))
            {
                decrypt2 = decrypt2.Substring(0, decrypt2.LastIndexOf('|'));
            }

        }


        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="clearText"></param>
        /// <returns></returns>
        public static string Decrypt(string dataToDecrypt)
        {
            try
            {
                byte[] decryptedData;
                using (RSACryptoServiceProvider RSA = RsaProviderFromPrivateKeyInPemFile())
                {
                    decryptedData = RSA.Decrypt(Convert.FromBase64String(dataToDecrypt), false);
                }
                return Encoding.UTF8.GetString(decryptedData);
            }
            catch (Exception ex)
            {
                return dataToDecrypt;
            }
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="clearText"></param>
        /// <returns></returns>
        public static string Encrypt(string data)
        {
            byte[] encryptData;
            using (RSACryptoServiceProvider RSA = RsaProviderFromPrivateKeyInPemFile())
            {
                encryptData = RSA.Encrypt(Encoding.UTF8.GetBytes(data), false);
            }
            return Convert.ToBase64String(encryptData);
        }

        private static RSACryptoServiceProvider RsaProviderFromPrivateKeyInPemFile()
        {
            string privateKey = @"-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANQvwNsEmjZYrz6K
hVHdCngHl615M8Pw+JJuDccRPo0oZ3YfTNk0ckcscbVBns8doh6QuVJN1mzRprXJ
q3HISOI6SwKDtcwXpYpvxBe6T1vBUb+ydaGzaIOqrpwag/RsVn6HZeT3nQVWDigO
Zn5R7Nsz70WKs9xIlZQoOF7tpTA/AgMBAAECgYAV2QTmiEbIqcEBk4m+sB/P1BhO
CFjIKBuwGBzbDm9+YVal1vs2sivCIFVk8GjFsqtqskQisVkOw1eDCEza3mCCmrbf
3dRUlE+V6MLSAR+8oqttcZXFPUbui8o0nUZgr2TNoVAuHiVGVtsEJ0K0XBSitUlw
skcsS2RorHL2PQIyoQJBAOovbO56PX34/zkeasD5VRMd4bSK+XX+zzufe3712Uvr
ByF++zxKIZbPwBo62HguCD5t/5xbGt840J6z5gzmet0CQQDn87puYKTiDUZ1Sqxe
fIDmCzG3/YTET5xasj3qMvt+5xpLu4jT7hwxTq5HX0G+FuJdS6FyOKOSTszpvW1/
dR/LAkBPL1oWCR9hySADoFVYivZJUIFRGuzfCRnpfzOy6k5fbUkr+lPZPve8luLN
+7fWazo+YdNcezHK6NshzpKrKgPBAkEAn49nUSTEaAiPzoHm3zywgw9yTUpluZG2
UiHJO8GEhkC+Mxi3wGpNFJI2izx5AiXF5D3xupxB0ZTJm4VGvOY6TwJAN7bJV3U4
iyzlvOxAo+RRCExV3FcWM3hR4a0ZCSjo3FSuvPnfOYxwGZJlHHN+gahDwhU4/duB
dBvPG+UBCMAAYw==
-----END PRIVATE KEY-----";
            using (var privateKeyTextReader = new StringReader(privateKey))
            {
                PemReader pr = new PemReader(privateKeyTextReader);
                RsaPrivateCrtKeyParameters keyPair = (RsaPrivateCrtKeyParameters)pr.ReadObject();
                RSAParameters rsaParams = DotNetUtilities.ToRSAParameters(keyPair);

                RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
                csp.ImportParameters(rsaParams);
                return csp;
            }
        }


        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="clearText"></param>
        /// <returns></returns>
        public static string RsaEncryptWithPublic(string clearText)
        {

            byte[] encryptData;
            using (RSACryptoServiceProvider RSA = PublicKeyFromPemFile())
            {
                encryptData = RSA.Encrypt(Encoding.UTF8.GetBytes(clearText), false);
            }
            return Convert.ToBase64String(encryptData);
        }

        private static RSACryptoServiceProvider PublicKeyFromPemFile()
        {
            var key = "-----BEGIN PUBLIC KEY-----\n";
            key += "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDUL8DbBJo2WK8+ioVR3Qp4B5et\n";
            key += "eTPD8PiSbg3HET6NKGd2H0zZNHJHLHG1QZ7PHaIekLlSTdZs0aa1yatxyEjiOksC\n";
            key += "g7XMF6WKb8QXuk9bwVG/snWhs2iDqq6cGoP0bFZ+h2Xk950FVg4oDmZ+UezbM+9F\n";
            key += "irPcSJWUKDhe7aUwPwIDAQAB\n";
            key += "-----END PUBLIC KEY-----";
            using (TextReader publicKeyTextReader = new StringReader(key))
            {
                RsaKeyParameters publicKeyParam = (RsaKeyParameters)new PemReader(publicKeyTextReader).ReadObject();

                RSACryptoServiceProvider cryptoServiceProvider = new RSACryptoServiceProvider();
                RSAParameters parms = new RSAParameters();

                parms.Modulus = publicKeyParam.Modulus.ToByteArrayUnsigned();
                parms.Exponent = publicKeyParam.Exponent.ToByteArrayUnsigned();

                cryptoServiceProvider.ImportParameters(parms);

                return cryptoServiceProvider;
            }
        }


        public static long GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds * 1000);
        }

    }
}
